package com.movie.service;

import com.movie.dto.UserFavoriteDTO;
import com.movie.entity.UserFavorite;
import com.movie.entity.User;
import com.movie.entity.Movie;
import com.movie.repository.UserFavoriteRepository;
import com.movie.repository.UserRepository;
import com.movie.repository.MovieRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class UserFavoriteService {

    private final UserFavoriteRepository userFavoriteRepository;
    private final UserRepository userRepository;
    private final MovieRepository movieRepository;

    @Transactional
    // 添加收藏
    public UserFavoriteDTO addFavorite(Long userId, Long movieId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Movie movie = movieRepository.findById(movieId)
                .orElseThrow(() -> new RuntimeException("电影不存在"));

        // 检查是否已经收藏
        if (userFavoriteRepository.existsByUser_IdAndMovie_Id(userId, movieId)) {
            throw new RuntimeException("已经收藏过该电影");
        }

        UserFavorite favorite = new UserFavorite();
        favorite.setUser(user);
        favorite.setMovie(movie);

        UserFavorite saved = userFavoriteRepository.save(favorite);
        return convertToDTO(saved);
    }
    @Transactional
    // 删除收藏
    public void removeFavorite(Long userId, Long movieId) {
        if (!userFavoriteRepository.existsByUser_IdAndMovie_Id(userId, movieId)) {
            throw new RuntimeException("收藏记录不存在");
        }
        userFavoriteRepository.deleteByUser_IdAndMovie_Id(userId, movieId);
    }

    @Transactional
    // 批量删除收藏
    public void batchRemove(Long userId, List<Long> movieIds) {
        if (movieIds == null || movieIds.isEmpty()) {
            throw new RuntimeException("电影ID列表不能为空");
        }
        // 校验全部存在，避免部分删除导致数据不一致
//        List<Long> notExists = movieIds.stream()
//                .filter(mid -> !userFavoriteRepository.existsByUser_IdAndMovie_Id(userId, mid))
//                .collect(Collectors.toList());
//        if (!notExists.isEmpty()) {
//            throw new RuntimeException("以下电影未收藏，无法取消：" + notExists);
//        }
        userFavoriteRepository.deleteBatchByUserIdAndMovieIds(userId, movieIds);
    }

    // 获取用户收藏列表
    public List<UserFavoriteDTO> getUserFavorites(Long userId) {
        return userFavoriteRepository.findByUser_Id(userId).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    // 检查是否收藏
    public boolean isFavorite(Long userId, Long movieId) {
        return userFavoriteRepository.existsByUser_IdAndMovie_Id(userId, movieId);
    }

    // 统计用户收藏数量
    public long countUserFavorites(Long userId) {
        return userFavoriteRepository.countByUser_Id(userId);
    }

    private UserFavoriteDTO convertToDTO(UserFavorite favorite) {
        UserFavoriteDTO dto = new UserFavoriteDTO();
        dto.setId(favorite.getId());
        dto.setUserId(favorite.getUser().getId());
        dto.setUsername(favorite.getUser().getUsername());
        dto.setMovieId(favorite.getMovie().getId());
        dto.setMovieTitle(favorite.getMovie().getTitle());
        dto.setMovieCover(favorite.getMovie().getCover());
        dto.setCreatedAt(favorite.getCreatedAt());
        dto.setMovieYear(favorite.getMovie().getYear());
        return dto;
    }
}